{% extends "base.html" %}
{% block content %}
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">基本信息</div>
        <div class="panel-body">
            <div class="container mt-3">
                <div class="container d-flex justify-content-center">
                    <form method="post" enctype="multipart/form-data" style="width: 100%; max-width: 800px;">
                        {% csrf_token %}
                        <div class="row container">
                            <div class="col-12 col-md-6">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3" style="margin-top:20px;">
                                            <label for="customer_name" class="form-label">客户名称:</label>
                                            <input type="text" class="form-control" id="customer_name"
                                                name="customer_name" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3" style="margin-top:20px;">
                                            <label for="report_date" class="form-label">报告日期:</label>
                                            <input type="date" class="form-control" id="report_date" name="report_date"
                                                required>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3" style="margin-top:20px;">
                                            <label for="instrument_model" class="form-label">仪器型号:</label>
                                            <select class="form-control" id="instrument_model" name="instrument_model"
                                                required>
                                                {% for instrument in instrument_models %}
                                                <option value="{{ instrument }}">{{ instrument }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>

                                </div>
                                <div class="row">

                                    <div class="col-md-6">
                                        <div class="mb-3" style="margin-top:20px;">
                                            <label for="before_clean_images" class="form-label">清洁前:</label>
                                            <input type="file" id="before_clean_images" name="before_clean_images"
                                                class="image-upload" accept="image/*" multiple>
                                            <div class="image-preview-container" id="beforeCleanPreview"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3" style="margin-top:20px;">
                                            <label for="after_clean_images" class="form-label">清洁后:</label>
                                            <input type="file" id="after_clean_images" name="after_clean_images"
                                                class="image-upload" accept="image/*" multiple>
                                            <div class="image-preview-container" id="afterCleanPreview"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div style="margin-top:20px;">
                            <div id="template_container"></div>
                        </div>


                        <div class="text-center mt-4" style="margin-top:20px;">
                            <button type="submit" class="btn btn-primary">生成报告</button>
                            <a href="{% url 'report_list' %}" class="btn btn-success mt-2">查看报告</a>
                        </div>
                    </form>
                </div>

            </div>
        </div>
    </div>
</div>
{% endblock %}
<script src="/static/bootstrap/js/jquery.min.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
{% block js %}
<style>
    .preview-image {
        max-width: 100px;
        max-height: 100px;
        margin: 5px;
    }

    .image-preview-container {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
    }

    .preview-item {
        position: relative;
    }

    .remove-image {
        position: absolute;
        top: 0;
        right: 0;
        padding: 0 4px;
        font-size: 12px;
        line-height: 1;
        border-radius: 50%;
        width: 18px;
        height: 18px;
        text-align: center;
    }
    
    
    .rotate-image {
        position: absolute;
        top: 0;
        left: 0;
        padding: 0 4px;
        font-size: 12px;
        line-height: 1;
        border-radius: 50%;
        width: 18px;
        height: 18px;
        text-align: center;
    }
</style>
<script>
    $(document).ready(function() {
        // 清洁前图片上传预览功能
        $('#before_clean_images').on('change', function() {
            handleImagePreview(this, '#beforeCleanPreview');
        });
        
        // 清洁后图片上传预览功能
        $('#after_clean_images').on('change', function() {
            handleImagePreview(this, '#afterCleanPreview');
        });
        
        function handleImagePreview(fileInput, previewContainer) {
            var files = fileInput.files;
            var previewDiv = $(previewContainer);
            
            // 获取已存在的文件名，避免重复
            var existingFiles = new Set();
            previewDiv.find('.preview-item img').each(function () {
                existingFiles.add($(this).data('filename'));
            });

            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                
                // 跳过已经显示的文件
                if (existingFiles.has(file.name)) {
                    continue;
                }
                
                if (file.type.match('image.*')) {
                    var reader = new FileReader();
                    
                    reader.onload = (function(theFile) {
                        return function(e) {
                            var previewItem = $('<div>').addClass('preview-item');
                            var img = $('<img>').attr('src', e.target.result).addClass('preview-image').data('filename', theFile.name);
                            
                            // 添加旋转按钮，指定type="button"防止触发表单提交
                            var rotateBtn = $('<button>').html('&#8635;').addClass('btn btn-sm btn-info rotate-image').attr('type', 'button').click(function() {
                                var currentRotation = parseInt(img.data('rotation')) || 0;
                                currentRotation = (currentRotation + 90) % 360;
                                img.data('rotation', currentRotation);
                                
                                // 应用旋转
                                var rotationTransform = 'rotate(' + currentRotation + 'deg)';
                                img.css({
                                    'transform': rotationTransform,
                                    'transition': 'transform 0.3s ease'
                                });
                                
                                // 真正旋转图片并更新文件
                                if(currentRotation !== 0) {
                                    rotateImageFile(theFile, currentRotation, function(rotatedFile) {
                                        // 更新预览图片
                                        var rotatedReader = new FileReader();
                                        rotatedReader.onload = function(e) {
                                            img.attr('src', e.target.result);
                                        };
                                        rotatedReader.readAsDataURL(rotatedFile);
                                        
                                        // 更新文件列表中的文件
                                        var filesArray = Array.from(fileInput.files);
                                        var index = filesArray.findIndex(f => f.name === theFile.name);
                                        
                                        if (index > -1) {
                                            filesArray[index] = rotatedFile;
                                            
                                            // 更新文件输入框的files属性
                                            var newFileList = new DataTransfer();
                                            filesArray.forEach(f => newFileList.items.add(f));
                                            fileInput.files = newFileList.files;
                                        }
                                    });
                                }
                            });
                            
                            var removeBtn = $('<button>').text('×').addClass('btn btn-sm btn-danger remove-image').attr('type', 'button').click(function() {
                                // 从文件列表中移除对应文件
                                var filesArray = Array.from(fileInput.files);
                                var index = filesArray.findIndex(f => f.name === theFile.name);
                                
                                if (index > -1) {
                                    filesArray.splice(index, 1);
                                    
                                    // 更新文件输入框的files属性
                                    var newFileList = new DataTransfer();
                                    filesArray.forEach(f => newFileList.items.add(f));
                                    fileInput.files = newFileList.files;
                                    
                                    // 移除预览项
                                    previewItem.remove();
                                }
                            });
                            
                            previewItem.append(img).append(rotateBtn).append(removeBtn);
                            previewDiv.append(previewItem);
                        };
                    })(file);
                    
                    reader.readAsDataURL(file);
                }
            }
        }
        
        // 旋转图片文件的函数
        function rotateImageFile(file, degrees, callback) {
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            var img = new Image();
            
            img.onload = function() {
                // 设置画布尺寸
                if (degrees % 180 === 0) {
                    canvas.width = img.width;
                    canvas.height = img.height;
                } else {
                    canvas.width = img.height;
                    canvas.height = img.width;
                }
                
                // 移动旋转中心到画布中心
                ctx.translate(canvas.width/2, canvas.height/2);
                ctx.rotate(degrees * Math.PI / 180);
                
                // 绘制图片
                ctx.drawImage(img, -img.width/2, -img.height/2);
                
                // 转换为Blob并回调
                canvas.toBlob(function(blob) {
                    // 修复：确保文件名和类型正确传递
                    var rotatedFile = new File([blob], file.name, {type: file.type, lastModified: Date.now()});
                    callback(rotatedFile);
                }, file.type);
            };
            
            img.src = URL.createObjectURL(file);
        }
    });
</script>
{% endblock %}